import { createStore } from 'vuex'

interface TabItem{
  key: string;
  title: string;
  closable: boolean
}

interface State {
  tabs:TabItem[];
  activeKey: string;
}

export default createStore<State>({
  state: {
    tabs: [],
    activeKey: ''
  },
  getters: {
    tabs: state => state.tabs,
    activeKey: state => state.activeKey
  },
  mutations: {
    addTab(state, tab: TabItem){
      //去掉首页
      if(tab.key === '/') return;
      const exists = state.tabs.some(
        item => item.key === tab.key
      )
      if(!exists){
        state.tabs.push(tab)
      }
    },
    removeTab(state, key: string){
      //只剩下一个标签页时不删除
      if(state.tabs.length <=1 )return;
      const index = state.tabs.findIndex(
        item => item.key === key
      )
      if(index !== -1){
        state.tabs.splice(index,1)
      }
    },
    setActiveKey(state, key:string){
      state.activeKey = key
    },
    resetTabs(state){
      state.tabs = []
      state.activeKey = ''
    }
  },
  actions: {
    addTab({commit}, tab: TabItem){
      commit('addTab', tab)
    },
    removeTab({commit}, key: string){
      commit('removeTab', key)
    },
    setActiveKey({commit}, tab: TabItem){
      commit('setActiveKey', tab)
    },
    resetTabs({commit}, key: string){
      commit('resetTabs', key)
    }
  },
  modules: {
  }
})
